package cn.jsxz.common.utils;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;


public class weixinutils {


    public static DefaultHttpClient httpclient;// http客户端

//	static {
//		ClientConnectionManager cm = new ThreadSafeClientConnManager();
//		httpclient = new DefaultHttpClient(cm);
//		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
//	}
//	

    /**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public static Map<String, String> getUserInfoAccessToken(String code, String appid, String AppSecret) {
        JsonObject object = null;
        Map<String, String> data = new HashMap<>();
        try {
            String url = String.format("https://api.WeiXinUtil.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    appid, AppSecret, code);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);
            data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
            data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 网页授权获取用户信息
     * 获取用户信息
     *
     * @param accessToken 网页授权获取的 token
     * @param openId
     * @return
     */
    public static Map<String, String> getAutoUserInfo(String accessToken, String openId) {
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        JsonObject userInfo = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            userInfo = token_gson.fromJson(response, JsonObject.class);
            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
            data.put("sex", userInfo.get("sex").toString().replaceAll("\"", ""));
            data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 获access_token
     *
     * @param wx_appid
     * @param wx_appsecret
     * @return
     */
    public static Map<String, String> getAccessToken(String wx_appid, String wx_appsecret) {
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wx_appid + "&secret=" + wx_appsecret;

        JsonObject accessTokenInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("获取Token-------------------" + response);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);
            data.put("access_token", accessTokenInfo.get("access_token").toString().replaceAll("\"", ""));
            data.put("expires_in", accessTokenInfo.get("expires_in").toString().replaceAll("\"", ""));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 获取jsapi_ticket
     *
     * @return
     */
    public static Map<String, String> getJsApiTicket(String accessToken) {
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        JsonObject jsApiTicket = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            jsApiTicket = token_gson.fromJson(response, JsonObject.class);
            data.put("ticket", jsApiTicket.get("ticket").toString().replaceAll("\"", ""));
            data.put("expires_in", jsApiTicket.get("expires_in").toString().replaceAll("\"", ""));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 全局Token 获取用户信息
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static Map<String, String> getUserInfo(String accessToken, String openId) {

        Map<String, String> data = new HashMap();
        // String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        JsonObject userInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");

            Gson token_gson = new Gson();

            userInfo = token_gson.fromJson(response, JsonObject.class);
            System.out.println(userInfo.toString());
            if (userInfo == null) {
                data.put("subscribe", "0");
            } else {
                data.put("subscribe", userInfo.get("subscribe").toString().replaceAll("\"", ""));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    public static void main(String[] args) {
        Map<String, String> map = weixinutils.getAccessToken("wxcb8eac513f4750e6", "8f8af1706029bb977d8aff46dcaf386a");
        // System.out.println(map.get("access_token"));
        Map<String, String> maps = weixinutils.getJsApiTicket(map.get("access_token"));
        System.out.println(maps.toString());

        //Map<String, String> data =	weixinutils.getUserInfo("10_iAXqdj6qUEqRrm0o3HGrPuXopE0-umZ2j5fhQjlynXZSJ2BrOa2Ay8QHt41ua8ItoxHVxvQda4PPa3hWuVstJ2cwV1G6XS9G3PLP66dajn1JV8stRohtqGprv-0j7FuxMFlWjty51e6SDHA9RLCbAJAEYP", "oGzeXwHBHSlNPJEvQNiqz3OM5LpY1");
        // System.out.println(data.toString());
    }


//    /**
//	 * 创建菜单
//	 */
//	public static String createMenu(String params, String accessToken) throws Exception {
//		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
//		httpost.setEntity(new StringEntity(params, "UTF-8"));
//		HttpResponse response = httpclient.execute(httpost);
//		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
//		JSONObject object = JSON.parseObject(jsonStr);
//		return object.getString("errmsg");
//	}
//    



    /* *//**
     * 获取access_token 
     * @param appid 凭证 
     * @param appsecret 密钥 
     * @return
     *//*  
    public static String getAccessToken(String appid, String appsecret) {  
        String result = HttpRequestUtil.getAccessToken(appid,appsecret);  
        JSONObject jsonObject = JSONObject.fromObject(result);  
        if (null != jsonObject) {  
            try {  
                result = jsonObject.getString("access_token");  
            } catch (JSONException e) {  
               logger.info("获取token失败 errcode:"+jsonObject.getInt("errcode") +",errmsg:"+ jsonObject.getString("errmsg"));                
            }  
        }  
        return result;  
    }  
    */


}
